package repositories

import (
	"Doge/config/db"
	"Doge/models"
	"Doge/modules/delayed/common"
	"Doge/modules/delayed/master"
	"gorm.io/gorm"
)

type DelayedManager struct {
	db *db.DB
}

func NewDelayedManager() (delayedManager *DelayedManager, err error) {
	var (
		selfDB *db.DB
	)

	if selfDB, err = db.NewDB(); err != nil {
		return &DelayedManager{}, err
	}
	return &DelayedManager{
		db: selfDB,
	}, err
}

func (manager *DelayedManager) InsertDelayed(delayed *models.Delayed) (id string, err error) {
	var (
		result *gorm.DB
		etcdJob  common.Job
	)

	result = manager.db.Db.Create(delayed)
	if result.RowsAffected == 1 {
		//同步到etcd
		etcdJob = common.Job{
			Name:     delayed.ID,
			Command:  delayed.Command,
			RunAt: delayed.RunAt,
		}
		err = master.G_jobMgr.SaveJob(&etcdJob)
		return delayed.ID, err
	}
	return "", result.Error

}


